/**********************************************************/
/* Goblin Defense - A tower defense game for Wii Homebrew */
/* Copyright (C) 2009 Ricardo Bueno Cordeiro              */
/* Licensed under de GNU General Public License v2.0      */
/*   See license_gplv2.txt for detalis                    */
/**********************************************************/

#include <gccore.h>
#include <math.h>

#include "sprite.h"
#include "draw.h"
#include "spritetex.h"

void Sprite::draw_sprite_error(f32 x, f32 y, f32 w, f32 h, f32 rcos, f32 rsin) {
	f32 half_w = w / 2.0;
	f32 half_h = h / 2.0;

	f32 right_x = rcos * half_w;
	f32 right_y = rsin * half_w;
	f32 up_x = -rsin * half_h;
	f32 up_y = rcos * half_h;

	DR_set_error_texture();

	GX_Begin(GX_QUADS, GX_VTXFMT0, 4);

	GX_Position3f32(x - right_x + up_x, y - right_y + up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(0.0, 0.0);

	GX_Position3f32(x - right_x - up_x, y - right_y - up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(0.0, 1.0);

	GX_Position3f32(x + right_x - up_x, y + right_y - up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(1.0, 1.0);

	GX_Position3f32(x + right_x + up_x, y + right_y + up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(1.0, 0.0);

	GX_End();
}

void Sprite::draw_sprite(f32 x, f32 y, f32 w, f32 h, f32 rcos, f32 rsin, u32 sprite) {
	if (sprite >= NUM_SPRITES) {
		Sprite::draw_sprite_error(x, y, w, h, rcos, rsin);
		return;
	}

	f32 half_w = w / 2.0;
	f32 half_h = h / 2.0;

	f32 right_x = rcos * half_w;
	f32 right_y = rsin * half_w;
	f32 up_x = -rsin * half_h;
	f32 up_y = rcos * half_h;

	DR_set_sprite_texture();

	GX_Begin(GX_QUADS, GX_VTXFMT0, 4);

	GX_Position3f32(x - right_x + up_x, y - right_y + up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(tex_coord[sprite].x1, tex_coord[sprite].y1);

	GX_Position3f32(x - right_x - up_x, y - right_y - up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(tex_coord[sprite].x2, tex_coord[sprite].y2);

	GX_Position3f32(x + right_x - up_x, y + right_y - up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(tex_coord[sprite].x3, tex_coord[sprite].y3);

	GX_Position3f32(x + right_x + up_x, y + right_y + up_y, 0.0);
	GX_Color4u8(255, 255, 255, 255);
	GX_TexCoord2f32(tex_coord[sprite].x4, tex_coord[sprite].y4);

	GX_End();
}

void Sprite::draw_sprite(f32 x, f32 y, f32 w, f32 h, u32 sprite) {
	Sprite::draw_sprite(x, y, w, h, 1.0, 0.0, sprite);
}
	
void Sprite::draw_sprite(f32 x, f32 y, f32 w, f32 h, f32 angle, u32 sprite) {
	Sprite::draw_sprite(x, y, w, h, cos(angle), sin(angle), sprite);
}
